<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>10-碰撞检测.html</title>
    <script src="js/event.js"></script>
    <script src="js/drag.js"></script>
    <script src="js/dragEl.js"></script>
    <script src="js/dragSelect.js"></script>
    <style>
      #box {
        position: absolute;
        left: 0;
        top: 0;
        width: 100px;
        height: 100px;
        background: red;
      }
      #box2 {
        position: absolute;
        left: calc(50% - 100px);
        top: calc(50% - 100px);
        width: 100px;
        height: 100px;
        background: yellow;
        z-index: 2;
      }
      .box3 {
        float: left;
        margin-right: 50px;
        width: 100px;
        height: 100px;
        background: blue;
        z-index: 2;
      }
    </style>
  </head>
  <body>
    <div id="box"></div>
    <div id="box2"></div>
    <div class="box3"></div>
    <div class="box3"></div>
    <div class="box3"></div>
    <div class="box3"></div>
    <div class="box3"></div>
    <script>
      function boom(el1, el2) {
        let el1Rect = el1.getBoundingClientRect();
        let el2Rect = el2.getBoundingClientRect();
        if (
          el1Rect.right < el2Rect.left ||
          el1Rect.left > el2Rect.right ||
          el1Rect.bottom < el2Rect.top ||
          el1Rect.top > el2Rect.bottom
        ) {
          return false;
        }
        return true;
      }
      {
        let box = document.querySelector("#box");
        let box2 = document.querySelector("#box2");
        let box3 = document.querySelectorAll(".box3");
        let boxDrag = new DragEl(box);
        boxDrag.on("dragmove", () => {
          if (boom(box, box2)) {
            box.style.background = "green";
          } else {
            box.style.background = "red";
          }
          box3.forEach((item) => {
            if (boom(box, item)) {
              // box.style.background = "green"; // 经过循环后，依旧是未碰撞的情况
              item.style.background = "green";
            } else {
              item.style.background = "blue";
            }
          });
        });
      }
    </script>
  </body>
</html>
